import { login, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {}

  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    removeToken()
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_INFO: (state, val) => {
    state.userInfo = val
  }
  // SET_AVATAR: (state, avatar) => {
  //   state.avatar = avatar
  // }
}

const actions = {
  // user login
  // 第一个参数是store
  login: function({ commit }, userInfo) {
    const { mobile, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ mobile: mobile, password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data)
        setToken(data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        // 把用户信息保存到vuex中
        commit('SET_USER_INFO', data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {

  },

  // remove token
  resetToken({ commit }) {

  }
}

export default {
  // 开启命名空间
  namespaced: true,
  // 数据 第一个参数是store
  state,
  // 同步 第一个参数是state
  mutations,
  // 异步 第一个参数是store
  actions
}

